package model

import "github.com/jinzhu/gorm"

const (
	NoRank int = iota
	StudentRank
	TeacherRank
	ManagerRank
)

type Account struct {
	*Model
	Username string `json:"username"`
	Password string `json:"password"`
	Rank     int    `json:"rank"`
}

func (a *Account) TableName() string {
	return "account"
}

func (a *Account) Create(db *gorm.DB) error {
	return db.Create(a).Error
}

func (a *Account) Get(db *gorm.DB) (*Account, error) {
	account := &Account{}
	db = db.Where("username = ? AND password = ? AND is_del = ?",
		a.Username,
		a.Password,
		0,
	)
	err := db.First(account).Error
	return account, err
}

func (a *Account) GetByUsername(db *gorm.DB) (*Account, error) {
	account := &Account{}
	db = db.Where("username = ? AND is_del = ?",
		a.Username,
		0,
	)
	err := db.First(account).Error
	return account, err
}

func (a *Account) List(db *gorm.DB, pageOffset, pageSize int) ([]*Account, error) {
	var users []*Account
	var err error
	if pageOffset >= 0 && pageSize > 0 {
		db = db.Offset(pageOffset).Limit(pageSize)
	}
	if a.Rank != 0 {
		db = db.Where("rank = ?", a.Rank)
	}
	if err = db.Where("is_del = ?", 0).Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}

func (a *Account) Delete(db *gorm.DB) error {
	return db.Where("id = ? AND is_del = ?", a.ID, 0).Delete(a).Error
}

func (a *Account) Update(db *gorm.DB, values map[string]interface{}) error {
	return db.Model(a).Where("id = ? AND is_del = ?", a.ID, 0).Update(values).Error
}
